import { BaseModel } from './BaseModel.js';
import { dataFiles } from '../config/database.js';

const defaultAttendances = [];

export class Attendance extends BaseModel {
    constructor() {
        super(dataFiles.attendance, defaultAttendances);
    }

    // 根据学生ID查找考勤记录
    findByStudentId(studentId) {
        const data = this.findAll();
        return data.filter(attendance => attendance.studentId === String(studentId));
    }

    // 根据班级查找考勤记录
    findByClassName(className) {
        const data = this.findAll();
        return data.filter(attendance => attendance.className === className);
    }

    // 根据日期查找考勤记录
    findByDate(date) {
        const data = this.findAll();
        return data.filter(attendance => attendance.date === date);
    }

    // 根据课程名称查找考勤记录
    findByCourseName(courseName) {
        const data = this.findAll();
        return data.filter(attendance => attendance.courseName === courseName);
    }

    // 根据日期范围查找考勤记录
    findByDateRange(startDate, endDate) {
        const data = this.findAll();
        return data.filter(attendance => {
            const attendanceDate = new Date(attendance.date);
            const start = new Date(startDate);
            const end = new Date(endDate);
            return attendanceDate >= start && attendanceDate <= end;
        });
    }

    // 批量删除考勤记录
    deleteMany(ids) {
        try {
            const data = this.findAll();
            const filteredData = data.filter(item => !ids.includes(parseInt(item.id)));

            if (filteredData.length === data.length) {
                return false; // 没有找到要删除的记录
            }

            this.saveData(filteredData);
            return true;
        } catch (error) {
            console.error(`Error deleting items with ids ${ids}:`, error);
            return false;
        }
    }
}
